package com.example.wangning.mycarofcountry.recommend.newest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.example.mycarofcountry.entity.dao.Recommend_Focusing;
import com.example.mycarofcountry.entity.dao.Recommend_News;
import com.example.mycarofcountry.entity.dao.Recommend_Newslist;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.db.DaoHelper;
import com.example.wangning.mycarofcountry.listener.OnMyClickListener;
import com.example.wangning.mycarofcountry.tool.DividerItemDecoration;
import com.example.wangning.mycarofcountry.tool.MyDialog;
import com.example.wangning.mycarofcountry.tool.NetworkAvailableUtils;
import com.example.wangning.mycarofcountry.webview.WebViewActivity;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewestFragment extends Fragment implements OnMyClickListener {
    private ViewPager pager;//广告栏部分
    private ViewPagerAdapter viewPagerAdapter;//广告栏适配器对象
    private RecyclerView recyclerView;//列表
    private NewlistAdapter newlistAdapter;
    private VolleySingleton queue;//定义一个请求队列
    private Handler handler;//定义一个handler对象，实现广告轮播
    private int currentItem = 0;
    private int maxItem = 6;
    private DaoHelper helper;
    private MyDialog myDialog;
    private String url = "http://app.api.autohome.com.cn/autov4.8.5/news/newslist-pm2-c0-nt0-p1-s20-l0.json";
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 设置当前左右滑动组件的下标为1，即第二张图片
            currentItem++;
            pager.setCurrentItem(currentItem % maxItem);

            handler.postDelayed(runnable, 4000);
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mewest, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pager = (ViewPager) view.findViewById(R.id.viewPager);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (NetworkAvailableUtils.isNetworkAvailable(getView().getContext())) {
            Toast.makeText(getView().getContext(), "当前网络状态良好", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getView().getContext(), "当前无网络连接，请检查网络状态", Toast.LENGTH_LONG).show();
        }
        helper = DaoHelper.getInstance();
        viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
        pager.setAdapter(viewPagerAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        newlistAdapter = new NewlistAdapter(getActivity());
        recyclerView.setAdapter(newlistAdapter);
        newlistAdapter.setOnMyClickListener(this);
        RecyclerViewHeader header = (RecyclerViewHeader) getActivity().findViewById(R.id.header);
        header.attachTo(recyclerView, true);
        handler = new Handler();
        List<Recommend_Focusing> focusings = helper.seacherFocusimgList();
        List<Recommend_Newslist> newslists = helper.seacherNewestList();
        if (focusings == null || focusings.size() == 0){
            if (newslists == null || newslists.size() == 0){
                myDialog = new MyDialog(getActivity(),"正在加载...",R.drawable.anim_set);
                myDialog.setCanceledOnTouchOutside(true);//设置点击以外区域不消失属性
                myDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        myDialog.dismiss();
                    }
                }, 3000);
            }
        }
        initData(url);
    }




    private void initData(String url) {
        queue = VolleySingleton.getVolleyIntance();

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                NewestBean newestBean = gson.fromJson(response, NewestBean.class);
                ResultEntity resultEntity = newestBean.getResult();
                if (newestBean != null) {
                    List<Recommend_Newslist> newslistBeans = resultEntity.getNewslist();
                    if (newslistBeans != null && newslistBeans.size() > 0) {
                        // 将获取到的最新集合设置到适配器中
                        newlistAdapter.addData(newslistBeans);
                        helper.addNewestList(newslistBeans);
                    }
                    List<Recommend_Focusing> focusingBeans = resultEntity.getFocusimg();
                    if (focusingBeans != null && focusingBeans.size() > 0) {
                        // 给广告栏绑定数据
                        viewPagerAdapter.addData(focusingBeans);
                        helper.addFocusimgList(focusingBeans);
                        // 秒之后改变viewpager的下标
                        handler.postDelayed(runnable, 4000);
                    }

                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                newlistAdapter.addData(helper.seacherNewestList());
                viewPagerAdapter.addData(helper.seacherFocusimgList());
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        queue.addRequest(stringRequest);
    }


    @Override
    public void onMyItemClick(Long id) {
        Intent intent = new Intent(getActivity(), WebViewActivity.class);
        intent.putExtra("id",id);
        getActivity().startActivity(intent);
    }
}
